<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon user-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.userCount }}</div>
              <div class="stats-label">用户总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon interface-icon">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.interfaceCount }}</div>
              <div class="stats-label">接口总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon online-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.onlineCount }}</div>
              <div class="stats-label">在线接口</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon invoke-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalInvokes }}</div>
              <div class="stats-label">总调用次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>接口调用趋势</span>
            </div>
          </template>
          <div ref="invokeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>接口分类统计</span>
            </div>
          </template>
          <div ref="categoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新接口列表 -->
    <el-card class="recent-card">
      <template #header>
        <div class="card-header">
          <span>最新接口</span>
          <el-button type="primary" @click="$router.push('/interface')">查看更多</el-button>
        </div>
      </template>
      
      <el-table v-loading="recentLoading" :data="recentInterfaces" style="width: 100%">
        <el-table-column prop="name" label="接口名称" />
        <el-table-column prop="description" label="接口描述" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)">{{ row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { User, Connection, CircleCheck, TrendCharts } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getUserCountUsingGET } from '@/api/user'
import { getInterfaceStatisticsUsingGET, getLatestInterfacesUsingGET } from '@/api/interfaceInfo'

// 统计数据
const stats = ref({
  userCount: 0,
  interfaceCount: 0,
  onlineCount: 0,
  totalInvokes: 0
})

// 最新接口列表
const recentInterfaces = ref([])
const recentLoading = ref(false)

const invokeChartRef = ref()
const categoryChartRef = ref()

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const typeMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return typeMap[method] || 'info'
}

// 获取用户总数
const getUserCount = async () => {
  try {
    const response = await getUserCountUsingGET()
    stats.value.userCount = response.data || 0
  } catch (error) {
    console.error('获取用户总数失败:', error)
    ElMessage.error('获取用户总数失败')
  }
}

// 获取接口统计信息
const getInterfaceStatistics = async () => {
  try {
    const response = await getInterfaceStatisticsUsingGET()
    if (response.data && response.data.records && response.data.records.length > 0) {
      const interfaceStatis = response.data.records[0].interfaceStatis
      if (interfaceStatis) {
        stats.value.interfaceCount = interfaceStatis.total || 0
        stats.value.onlineCount = interfaceStatis.onlineTotal || 0
        stats.value.totalInvokes = interfaceStatis.invokeTotal || 0
      }
    }
  } catch (error) {
    console.error('获取接口统计失败:', error)
    ElMessage.error('获取接口统计失败')
  }
}

// 获取最新接口列表
const getLatestInterfaces = async () => {
  recentLoading.value = true
  try {
    const response = await getLatestInterfacesUsingGET()
    if (response.data && response.data.records) {
      recentInterfaces.value = response.data.records
    }
  } catch (error) {
    console.error('获取最新接口列表失败:', error)
    ElMessage.error('获取最新接口列表失败')
  } finally {
    recentLoading.value = false
  }
}

// 初始化调用趋势图表
const initInvokeChart = () => {
  const chart = echarts.init(invokeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '调用次数',
        type: 'line',
        smooth: true,
        data: [1200, 1800, 2200, 2800, 3200, 3800],
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化分类统计图表
const initCategoryChart = () => {
  const chart = echarts.init(categoryChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '接口分类',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 20, name: '用户管理' },
          { value: 15, name: '文件处理' },
          { value: 12, name: '数据分析' },
          { value: 8, name: '消息通知' },
          { value: 5, name: '其他' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 加载所有数据
const loadDashboardData = async () => {
  await Promise.all([
    getUserCount(),
    getInterfaceStatistics(),
    getLatestInterfaces()
  ])
}

onMounted(async () => {
  // 加载数据
  await loadDashboardData()
  
  // 初始化图表
  await nextTick()
  initInvokeChart()
  initCategoryChart()
})
</script>

<style scoped lang="scss">
.dashboard {
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stats-card {
    .stats-content {
      display: flex;
      align-items: center;
      
      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
        
        &.user-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.interface-icon {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.online-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.invoke-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
      
      .stats-info {
        .stats-number {
          font-size: 24px;
          font-weight: 600;
          color: #333;
          line-height: 1;
        }
        
        .stats-label {
          font-size: 14px;
          color: #666;
          margin-top: 4px;
        }
      }
    }
  }
  
  .charts-row {
    margin-bottom: 20px;
  }
  
  .chart-card {
    .chart-container {
      height: 300px;
    }
  }
  
  .recent-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
